import subprocess
import sys
import time
import os
import threading

def print_output(process, prefix):
    """打印进程输出"""
    for line in process.stdout:
        print(f"{prefix}: {line.strip()}")
    for line in process.stderr:
        print(f"{prefix} ERROR: {line.strip()}")

def start_server(script_name, description):
    """启动一个服务器进程"""
    print(f"正在启动{description}...")
    try:
        # 使用python解释器启动脚本
        process = subprocess.Popen([sys.executable, script_name],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 universal_newlines=True,
                                 bufsize=1)  # 行缓冲
        
        # 创建线程来打印输出
        threading.Thread(target=print_output, 
                        args=(process, description),
                        daemon=True).start()
        
        print(f"{description}已启动，进程ID: {process.pid}")
        return process
    except Exception as e:
        print(f"启动{description}时出错: {str(e)}")
        return None

def main():
    # 获取当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 启动Flask服务器（使用根目录的app.py）
    flask_process = start_server(
        os.path.join(current_dir, 'app.py'),
        "Flask"
    )
    
    # 等待Flask服务器启动
    time.sleep(2)
    
    # 启动WebSocket服务器
    ws_process = start_server(
        os.path.join(current_dir, 'src', 'websocket_server.py'),
        "WebSocket"
    )
    
    try:
        # 保持脚本运行
        while True:
            time.sleep(1)
            # 检查进程是否还在运行
            if flask_process and flask_process.poll() is not None:
                print("Flask服务器已停止")
                break
            if ws_process and ws_process.poll() is not None:
                print("WebSocket服务器已停止")
                break
    except KeyboardInterrupt:
        print("\n正在关闭服务器...")
        # 关闭所有进程
        if flask_process:
            flask_process.terminate()
        if ws_process:
            ws_process.terminate()
        print("服务器已关闭")

if __name__ == "__main__":
    main() 